﻿using GrainManage.Data.Access;
using GrainManage.Data.Model;
using GrainManage.Data.Service.Util;
using System;
using System.Collections.Generic;
using System.Data;

namespace GrainManage.Data.Service
{
    public class BaseService
    {
        protected IAccess Proc { get; private set; }

        public BaseService(IAccess proc)
        {
            this.Proc = proc;
        }

        protected static int GetTotalRowCount(DataSet ds)
        {
            int totalRow = 0;
            if (ds != null && ds.Tables.Count > 1)
            {
                try
                {
                    totalRow = Convert.ToInt32(ds.Tables[1].Rows[0][0]);
                }
                catch
                {
                    totalRow = 0;
                }
            }
            return totalRow;
        }

        protected static int GetOffset(IPageable page)
        {
            return page.PageIndex * page.PageSize;
        }

        protected static DataRow GetFirstRow(DataSet ds)
        {
            DataRow firstRow = null;
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                firstRow = ds.Tables[0].Rows[0];
            }
            return firstRow;
        }

        protected static List<TModel> ConvertToModel<TModel>(DataSet ds, ICountable records) where TModel : class,new()
        {
            List<TModel> result = new List<TModel>();
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                result = Convertor.ConvertTo<TModel>(ds.Tables[0]);
            }
            if (records != null)
            {
                records.Total = GetTotalRowCount(ds);
            }
            return result;
        }

        protected static TModel ConvertToModel<TModel>(DataRow row) where TModel : class,new()
        {
            TModel result = default(TModel);
            if (row != null)
            {
                result = Convertor.ConvertTo<TModel>(row);
            }
            return result;
        }
    }
}
